// import { addRule, removeRule, rule, updateRule } from '@/services/ant-design-pro/api';
import { getMenurule, removeItem } from '@/services/menurule';
import { DeleteOutlined, ExportOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  // FooterToolbar,
  // ModalForm,
  PageContainer,
  // ProDescriptions,
  // ProFormText,
  // ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, message, Space, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import { FormattedMessage, useIntl, useAccess } from 'umi';
import { getTree } from '@/utils';
import SvgIcon from '@/components/SvgIcon';
import AddEdit from './components/AddEdit';
import ViewDetail from './components/ViewDetail';
import PermissionWrapper from '@/components/PermissionWrapper';

const { confirm } = Modal;

const Menu: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const access = useAccess();
  const [activeKey, setActiveKey] = useState<string>('menu,btn,tag');
  const [isPagination, setPagination] = useState<boolean>(false);

  const [viewDrawerVisible, handleDrawerVisible] = useState<boolean>(false);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const getList = async (params: API.RuleListItem & API.PageParams) => {
    const _params = {
      type: activeKey,
      ...params,
      _page: params.current || 1,
      _limit: params.pageSize || 20,
    };
    if (_params.type.startsWith('menu')) {
      setPagination(false);
      _params._all = 'ty';
    } else {
      setPagination(true);
    }
    delete _params.current;
    delete _params.pageSize;
    const { code, data } = await getMenurule(_params);
    const arr = getTree(data ? data.data : []);
    return {
      data: arr,
      total: data ? data.count : 0,
      success: code === 0,
    };
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.RuleListItem[]) => {
    if (!selectedRows) return;
    confirm({
      centered: true,
      content: intl.formatMessage({ id: 'public.deleteConfirmMessage' }),
      async onOk(): Promise<any> {
        if (!access.isAdmin) {
          message.warning(intl.formatMessage({ id: 'public.noDeletePermission' }));
          return false;
        }
        const hide = message.loading(intl.formatMessage({ id: 'public.deleteLoading' }));
        const { code } = await removeItem({
          id: selectedRows.map((row) => row.id),
        });
        hide();
        if (+code === 0) {
          message.success(intl.formatMessage({ id: 'public.successTips' }));
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.();
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const getColumns = (type: string): any[] => {
    return [
      {
        title: <FormattedMessage id="menurule.remark" />,
        dataIndex: 'remark',
        width: 240,
      },
      {
        title: <FormattedMessage id="menurule.id" />,
        dataIndex: 'id',
        width: 80,
        hideInSearch: true,
      },
      ...(type !== 'api'
        ? [
            {
              title: <FormattedMessage id="menurule.title" />,
              dataIndex: 'title',
              width: 120,
              hideInSearch: true,
            },

            {
              title: <FormattedMessage id="menurule.type" />,
              dataIndex: 'type',
              width: 120,
              valueType: 'select',
              valueEnum: {
                menu: {
                  text: <FormattedMessage id="menurule.menu" />,
                },
                btn: {
                  text: <FormattedMessage id="menurule.btn" />,
                },
                tag: {
                  text: <FormattedMessage id="menurule.tag" />,
                },
                api: {
                  text: <FormattedMessage id="menurule.api" />,
                },
              },
              fieldProps: {
                options: [
                  {
                    label: <FormattedMessage id="menurule.menu" />,
                    value: 'menu',
                  },
                  {
                    label: <FormattedMessage id="menurule.btn" />,
                    value: 'btn',
                  },
                  {
                    label: <FormattedMessage id="menurule.tag" />,
                    value: 'tag',
                  },
                ],
              },
            },
            {
              title: <FormattedMessage id="menurule.position" />,
              dataIndex: 'position',
              width: 120,
              // hideInSearch: true,
              valueEnum: {
                top: {
                  text: <FormattedMessage id="menurule.top" />,
                },
                left: {
                  text: <FormattedMessage id="menurule.left" />,
                },
                'table-top-left': {
                  text: <FormattedMessage id="menurule.table-top-left" />,
                },
                'table-top-right': {
                  text: <FormattedMessage id="menurule.table-top-right" />,
                },
                'td-operate': {
                  text: <FormattedMessage id="menurule.td-operate" />,
                },
              },
            },
            {
              title: <FormattedMessage id="menurule.icon" />,
              dataIndex: 'icon',
              width: 120,
              ellipsis: true,
              hideInSearch: true,
              align: 'center',
              render: (_, record) => {
                return <SvgIcon icon={record.icon} style={{ maxWidth: 48 }} />;
              },
            },
            {
              title: <FormattedMessage id="menurule.path" />,
              dataIndex: 'path',
              width: 180,
              ellipsis: true,
              copyable: true,
              hideInSearch: true,
            },
          ]
        : [
            {
              title: <FormattedMessage id="menurule.apiname" />,
              dataIndex: 'name',
              width: 120,
              hideInSearch: true,
            },
          ]),
      {
        title: <FormattedMessage id="menurule.api" />,
        dataIndex: 'api',
        width: 240,
        ellipsis: true,
        copyable: true,
        hideInSearch: true,
      },
      ...(type !== 'api'
        ? [
            {
              title: <FormattedMessage id="menurule.sort" />,
              dataIndex: 'sort',
              width: 80,
              hideInSearch: true,
            },
          ]
        : []),
      {
        title: <FormattedMessage id="public.status" />,
        dataIndex: 'status',
        width: 120,
        hideInSearch: true,
        valueEnum: {
          1: {
            text: <FormattedMessage id="menurule.visible" />,
            status: 'Success',
          },
          2: {
            text: <FormattedMessage id="menurule.hidden" />,
            status: 'Default',
          },
          3: {
            text: <FormattedMessage id="menurule.disabled" />,
            status: 'Default',
          },
        },
      },
      {
        title: <FormattedMessage id="public.updatetime" />,
        dataIndex: 'updatetime',
        valueType: 'dateTime',
        hideInSearch: true,
        width: 160,
      },
      {
        title: <FormattedMessage id="menurule.operate" />,
        dataIndex: 'option',
        valueType: 'option',
        width: 160,
        fixed: 'right',
        align: 'center',
        render: (_, record) => [
          <PermissionWrapper key="view" name="system.menurule.view">
            <a
              onClick={() => {
                setCurrentRow(record);
                handleDrawerVisible(true);
              }}
            >
              <FormattedMessage id="public.view" />
            </a>
          </PermissionWrapper>,
          <PermissionWrapper key="edit" name="system.menurule.edit">
            <a
              onClick={() => {
                setCurrentRow(record);
                handleModalVisible(true);
              }}
            >
              <FormattedMessage id="public.edit" />
            </a>
          </PermissionWrapper>,
          <PermissionWrapper key="delete" name="system.menurule.delete">
            <a key="delete" onClick={() => handleRemove([record])}>
              <FormattedMessage id="public.delete" />
            </a>
          </PermissionWrapper>,
        ],
      },
    ];
  };

  const columns: Record<string, ProColumns<API.RuleListItem>[]> = {
    'menu,btn,tag': getColumns('menu'),
    api: getColumns('api'),
  };

  return (
    <PageContainer
      // header={{ title: null }}
      tabList={[
        {
          key: 'menu,btn,tag',
          tab: <FormattedMessage id="menurule.menu-btn" />,
        },
        {
          key: 'api',
          tab: <FormattedMessage id="menurule.api" />,
        },
      ]}
      tabActiveKey={activeKey}
      onTabChange={(key) => {
        setActiveKey(key as string);
        actionRef.current?.reset?.();
      }}
    >
      <ProTable<API.RuleListItem, API.PageParams>
        scroll={{ x: 'max-content' }}
        headerTitle={
          <Space size={16}>
            <PermissionWrapper key="batchDelete" name="system.menurule.delete">
              <Button
                disabled={selectedRowsState?.length <= 0}
                type="default"
                icon={<DeleteOutlined />}
                onClick={() => handleRemove(selectedRowsState)}
              >
                <FormattedMessage id="public.batchDelete" />
              </Button>
            </PermissionWrapper>
            <Button
              disabled={selectedRowsState?.length <= 0}
              type="default"
              icon={<ExportOutlined />}
              onClick={() => {
                message.info(intl.formatMessage({ id: 'public.exportData' }));
              }}
            >
              <FormattedMessage id="public.exportData" />
            </Button>
          </Space>
        }
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          collapsed: false,
          collapseRender: () => null,
        }}
        toolbar={
          {
            // 方式一
            // multipleLine: true,
            // tabs: {
            //   activeKey,
            //   onChange: (key) => {
            //     setActiveKey(key as string);
            //     actionRef.current?.reset?.();
            //   },
            //   items: [
            //     {
            //       key: 'menu,btn,tag',
            //       tab: <FormattedMessage id="menurule.menu-btn" />,
            //     },
            //     {
            //       key: 'api',
            //       tab: <FormattedMessage id="menurule.api" />,
            //     },
            //   ],
            // },
            // 方式二
            // menu: {
            //   type: 'tab',
            //   activeKey,
            //   onChange: (key) => {
            //     setActiveKey(key as string);
            //     actionRef.current?.reset?.();
            //   },
            //   items: [
            //     {
            //       key: 'menu,btn,tag',
            //       label: <FormattedMessage id="menurule.menu-btn" />,
            //     },
            //     {
            //       key: 'api',
            //       label: <FormattedMessage id="menurule.api" />,
            //     },
            //   ],
            // },
          }
        }
        toolBarRender={() => [
          <PermissionWrapper key="add" name="system.menurule.add">
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCurrentRow(undefined);
                handleModalVisible(true);
              }}
              icon={<PlusOutlined />}
            >
              <FormattedMessage id="public.add" />
            </Button>
          </PermissionWrapper>,
        ]}
        options={false}
        request={getList}
        columns={columns[activeKey]}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        tableAlertRender={false}
        // tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
        //   <Space size={24}>
        //     <span>
        //       已选 {selectedRowKeys.length} 项
        //       <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
        //         取消选择
        //       </a>
        //     </span>
        //   </Space>
        // )}
        // tableAlertOptionRender={() => {
        //   return (
        //     <Space size={16}>
        //       <a>批量删除</a>
        //       <a>导出数据</a>
        //     </Space>
        //   );
        // }}
        dateFormatter="string"
        pagination={isPagination ? {} : false}
      />

      <AddEdit
        visible={createModalVisible}
        row={currentRow}
        defaultMenuType={activeKey === 'api' ? 'api' : 'menu'}
        onClose={() => handleModalVisible(false)}
        onSuccess={() => {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      />

      <ViewDetail
        visible={viewDrawerVisible}
        row={currentRow!}
        onClose={() => handleDrawerVisible(false)}
      />
    </PageContainer>
  );
};

export default Menu;
